﻿using Cxuu.Common;
using Cxuu.Models;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Repository
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ArticleRepository : BaseRepository<Article, PetaPocoContext>
    {

        public ArticleRepository(PetaPocoContext petaPocoContext) : base(petaPocoContext) { }


        /// <summary>
        /// 前台访问文章时 浏览量+1
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task IncHits(int? id)
        {
            Sql sql = Sql.Builder;
            sql.Append("SET Hits = Hits + 1")
                .Where("Id =@0", id);
            await CreateDAO().UpdateAsync<Article>(sql);
        }


        /// <summary>
        /// 前台查询一条
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ViewArticleAndContent> GetAsync(int? id)
        {
            Sql sql = Sql.Builder;
            sql.Select("*")
            .From("cxuu_article AS article")
            .LeftJoin("cxuu_article_content AS content")
            .On("article.Id = content.Aid")
            .Where("article.Id =@0", id)
            .Where("article.Status = 1");
            return await CreateDAO().FirstOrDefaultAsync<ViewArticleAndContent>(sql);
        }


        /// <summary>
        /// 编辑使用 查询一条
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<EditArticleAndContent> GetEditAsync(int? id)
        {
            Sql sql = Sql.Builder;

            sql.Select("*")
                .From("cxuu_article as article")
                .LeftJoin("cxuu_article_content as content")
                .On("article.Id=content.Aid")
                .Where("article.Id =@0", id);
            return await CreateDAO().FirstOrDefaultAsync<EditArticleAndContent>(sql);
        }


        /// <summary>
        /// 根据CID 查询一条 用于判断当前栏目下有没有数据
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        public async Task<Article> GetArticleByCidAsync(int cid)
        {
            Sql sql = Sql.Builder;
            sql.Select("*").From("cxuu_article").Where("Cid =@0", cid);
            return await CreateDAO().FirstOrDefaultAsync<Article>(sql);
        }

        /// <summary>
        /// 获取文章及栏目列表  后台使用
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="orderBy"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<Page<ViewArticleAndCate>> GetListAsync(int? cid, int page, int limit, string orderBy, string keyword, int status, int uid = 0)
        {
            Sql sql = Sql.Builder;
            sql.Select("article.Id,cate.Name as CateName,g.Groupname,u.Nickname,article.Cid,article.Title,article.Examine,article.Imgbl,article.Hits,article.Time,article.Status,article.AttA,article.AttB,article.AttC")
                .From("cxuu_article as article")
                .LeftJoin("cxuu_article_cate as cate").On("article.Cid = cate.Id");

            sql.LeftJoin("cxuu_admin_user u").On("article.Uid=u.Id");
            sql.LeftJoin("cxuu_admin_group g").On("u.Gid=g.Id");

            if (status != 2)
                sql.Where("article.Status = @0", status);

            if (uid != 0)
                sql.Where("article.Uid = @0", uid);

            if (cid > 0)
                sql.Where("article.Cid =@0", cid);

            if (!string.IsNullOrEmpty(keyword))
                sql.Where("article.Title like @0", "%" + keyword + "%");

            if (!string.IsNullOrEmpty(orderBy))
                sql.OrderBy(orderBy);

            return await CreateDAO().PageAsync<ViewArticleAndCate>(page, limit, sql);
        }

        /// <summary>
        /// 获取文章及栏目列表条数列表 前台使用
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="limit"></param>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        public async Task<List<ViewArticleAndCate>> GetListByLimtAsync(string cid, int limit, bool img, int att, string orderBy)
        {
            Sql sql = Sql.Builder;
            sql.Select("article.Id,cate.Name as CateName,article.Cid,article.Title,article.Examine,article.Img,article.Hits,article.Time,article.AttA,article.AttB,article.AttC")
                .From("cxuu_article as article")
                .LeftJoin("cxuu_article_cate as cate")
                .On("article.Cid = cate.Id")
                .Where("article.Status = 1");
            //属性
            if (att == 1)
                sql.Where("article.AttA = 1");

            if (att == 2)
                sql.Where("article.AttB = 1");

            if (att == 3)
                sql.Where("article.AttC = 1");
            //图片
            if (img)
                sql.Where("article.Imgbl = 1");

            if (cid != "0")
                sql.Where("article.Cid IN (" + cid + ")");

            if (!string.IsNullOrEmpty(orderBy))
                sql.OrderBy(orderBy);

            sql.Append("limit @0", limit);
            return await CreateDAO().FetchAsync<ViewArticleAndCate>(sql);
        }
        /// <summary>
        /// 前台搜索用
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<Page<ViewArticleAndCate>> GetListAsync(int page, int limit, string keyword)
        {
            Sql sql = Sql.Builder;
            sql.Select("A.Id,B.Name as CateName,A.Cid,A.Title,A.Examine,A.Time,A.Status")
                .From("cxuu_article as A")
                .LeftJoin("cxuu_article_cate as B").On("A.Cid = B.Id");

            sql.Where("A.Status = 1");

            if (!string.IsNullOrEmpty(keyword))
            {
                sql.Where("A.Title like @0", "%" + keyword + "%");
            }

            sql.OrderBy("A.Id");

            return await CreateDAO().PageAsync<ViewArticleAndCate>(page, limit, sql);
        }

        /// <summary>
        /// 插入一条信息
        /// </summary>
        /// <param name="article"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<Article> InsertArticleAndContentAsync(Article article, ArticleContent content)
        {
            var dao = CreateDAO();
            await dao.OpenSharedConnectionAsync();
            try
            {

                if (article.Img != null)
                    article.Imgbl = 1;

                var a = await dao.InsertAsync(article);

                if (content.Content != null)
                {
                    Sql sql = Sql.Builder;
                    sql.Append("INSERT INTO cxuu_article_content (Aid, Content) VALUES (@0,@1);", article.Id, content.Content);
                    await CreateDAO().ExecuteAsync(sql);
                }

                if (a != null)
                    return article;
            }
            finally
            {
                dao.CloseSharedConnection();
            }
            return null;
        }
        /// <summary>
        /// 更新一条信息
        /// </summary>
        /// <param name="article"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<int> UpdateArticleAndContentAsync(Article article, ArticleContent content)
        {
            if (article != null)
            {
                var dao = CreateDAO();
                if (content != null)
                {
                    ArticleContent ac = await dao.SingleOrDefaultAsync<ArticleContent>(article.Id);
                    if (ac != null)
                    {
                        ac.Content = content.Content;
                        await dao.UpdateAsync(ac);
                    }
                    else
                    {
                        Sql sql = Sql.Builder;
                        sql.Append("INSERT INTO cxuu_article_content (Aid, Content) VALUES (@0,@1);", article.Id, content.Content);
                        await CreateDAO().ExecuteAsync(sql);
                    }
                }
                Article a = await dao.SingleOrDefaultAsync<Article>(article.Id);
                a.Title = article.Title;
                a.Status = article.Status;
                a.Img = article.Img;
                a.Imgbl = article.Img != null ? 1 : 0;
                a.Cid = article.Cid;
                a.AttA = article.AttA;
                a.AttB = article.AttB;
                a.AttC = article.AttC;
                a.Examine = article.Examine;
                a.Attments = article.Attments;
                return await dao.UpdateAsync(a);
            }
            return 0;
        }

        public async Task<int> UpdateArticleAttAsync(int id, int status, string att)
        {
            Sql sql = Sql.Builder;
            switch (att)
            {
                case "AttA":
                    sql.Append("SET AttA = @0 WHERE Id=@1", status, id);
                    break;
                case "AttB":
                    sql.Append("SET AttB = @0 WHERE Id=@1", status, id);
                    break;
                case "AttC":
                    sql.Append("SET AttC = @0 WHERE Id=@1", status, id);
                    break;
                default:
                    sql.Append("SET Status = @0 WHERE Id=@1", status, id);
                    break;
            }
            return await CreateDAO().UpdateAsync<Article>(sql);
        }
    }
}
